import { _decorator, Color, Component, EditBox, instantiate, Label, Node, Prefab, Slider } from 'cc';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { EventManager } from '../event/EventManager';
import { Village } from '../entity/Village';
import { UserInfo } from '../common/UserInfo';
import VillageApi from '../api/VillageApi';
import { TraderEvent } from '../entity/TraderEvent';
import { Trader } from './Trader';
import { UIHeader } from '../common/UIHeader';
const { ccclass, property } = _decorator;

@ccclass('Transport')
export class Transport extends Component {
    @property(UIHeader)
    uiHeader:UIHeader
    @property(Label)
    traderDesc:Label
    @property(Label)
    traderNum:Label
    @property(Label)
    villageName:Label
    @property(Label)
    coord:Label
    @property(Node)
    openVillage:Node
    @property(Label)
    needTraderCount:Label
    @property(Slider)
    woodSlider:Slider
    @property(EditBox)
    woodEditBox:EditBox
    @property(Label)
    woodCount:Label
    @property(Slider)
    mudSlider:Slider
    @property(EditBox)
    mudEditBox:EditBox
    @property(Label)
    mudCount:Label
    @property(Slider)
    ironSlider:Slider
    @property(EditBox)
    ironEditBox:EditBox
    @property(Label)
    ironCount:Label
    @property(Slider)
    foodSlider:Slider
    @property(EditBox)
    foodEditBox:EditBox
    @property(Label)
    foodCount:Label
    @property(Node)
    submit:Node

    @property(Node)
    content:Node
    @property(Prefab)
    traderPrefab:Prefab

    private _village:Village
    private _traderPacket:number 
    private _traderNumCurrent:number
    private _traderNum:number
    private _wood:number
    private _mud:number
    private _iron:number
    private _food:number
    private _needTraderCount:number = 0
    private _traderList:Node[] = []
    private _traderBackList:TraderEvent[] = []

    start() {
        this.uiHeader.setData('运输物资')
        EventManager.instance.on('运输物资close', this.onClose, this)
       
        this.openVillage.on(Node.EventType.TOUCH_END, this.onOpenVillage, this)
        this.submit.on(Node.EventType.TOUCH_END, this.onSubmit, this)
        EventManager.instance.on(EventManager.EventType.SelectVillage, this.onSelectVillage, this)
        EventManager.instance.on(EventManager.EventType.TraderTimeDown, this.getMarketEvents, this)
        EventManager.instance.on(EventManager.EventType.TraderBack, this.onTraderBack, this)
        
        this.woodSlider.node.on('slide', this.onWoodSlide, this)
        this.mudSlider.node.on('slide', this.onMudSlide, this)
        this.ironSlider.node.on('slide', this.onIronSlide, this)
        this.foodSlider.node.on('slide', this.onFoodSlide, this)
        
        this.woodEditBox.node.on('editing-did-ended', this.onWoodEdit, this);
        this.mudEditBox.node.on('editing-did-ended', this.onMudEdit, this);
        this.ironEditBox.node.on('editing-did-ended', this.onIronEdit, this);
        this.foodEditBox.node.on('editing-did-ended', this.onFoodEdit, this);
        
        this.init()
    }

    protected onDisable(): void {
        EventManager.instance.off(EventManager.EventType.SelectVillage, this.onSelectVillage, this)
        EventManager.instance.off(EventManager.EventType.TraderTimeDown, this.getMarketEvents, this)
        EventManager.instance.off(EventManager.EventType.TraderBack, this.onTraderBack, this)
    }
    
    async init(){
        await UserInfo.instance.refreshVillageDetail()
        await this.getMarketEvents()
        this. _traderPacket = UserInfo.instance.traderPacket
        this. _traderNumCurrent = UserInfo.instance.traderNumCurrent
        this. _traderNum = UserInfo.instance.traderNum
        // this._village = null
        this._needTraderCount = 0
        let villageData = UserInfo.instance.villageData
        this._food = villageData.res.food_reserve
        this._iron = villageData.res.iron_reserve
        this._wood = villageData.res.wood_reserve
        this._mud = villageData.res.mud_reserve
         

        this.traderDesc.string = `每个商人可运载 ${this._traderPacket} 资源`
        this.traderNum.string = `${this._traderNumCurrent}/${this._traderNum}`
        
        if(!this._village){
            this.villageName.string = '请选择村庄'
            this.coord.string = ''
        }
        
        this.needTraderCount.string = ''
        this.woodCount.string = this._wood.toFixed()
        this.mudCount.string = this._mud.toFixed()
        this.ironCount.string = this._iron.toFixed()
        this.foodCount.string = this._food.toFixed()
        this.woodEditBox.string = '0'
        this.mudEditBox.string = '0'
        this.ironEditBox.string = '0'
        this.foodEditBox.string = '0'
        this.woodSlider.progress = 0
        this.mudSlider.progress = 0
        this.ironSlider.progress = 0
        this.foodSlider.progress = 0



    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.Transport)
    }

    onOpenVillage(){
        UIManager.instance.openUI(PrefabEnum.SelectVillage)
    }

    onSelectVillage(village:Village){
        this._village = village
        this.villageName.string = village.name
        this.coord.string = `(${village.x}|${village.y})`
    }

    onWoodSlide(slider: Slider){
        this.woodEditBox.string = Math.floor(this._wood * slider.progress) + ''

        this.setNeedTraderCount()
    } 
    onMudSlide(slider: Slider){
        this.mudEditBox.string = Math.floor(this._mud * slider.progress) + ''

        this.setNeedTraderCount()
    }  
    onIronSlide(slider: Slider){
        this.ironEditBox.string = Math.floor(this._iron * slider.progress) + ''

        this.setNeedTraderCount()
    } 
    onFoodSlide(slider: Slider){
        this.foodEditBox.string = Math.floor(this._food * slider.progress) + ''

        this.setNeedTraderCount()
    }

    onWoodEdit(editbox: EditBox){
        let str = editbox.string
        if(!/^\d+$/.test(str)){
            return
        }
        let num = parseInt(str)
        num = num > this._wood ? this._wood : num
        this.woodSlider.progress = num / this._wood
        editbox.string = num + ''

        this.setNeedTraderCount()
    } 
    onMudEdit(editbox: EditBox){
        let str = editbox.string
        if(!/^\d+$/.test(str)){
            return
        }
        let num = parseInt(str)
        num = num > this._mud ? this._mud : num
        this.mudSlider.progress = num / this._mud
        editbox.string = num + ''

        this.setNeedTraderCount()
    } 
    onIronEdit(editbox: EditBox){
        let str = editbox.string
        if(!/^\d+$/.test(str)){
            return
        }
        let num = parseInt(str)
        num = num > this._iron ? this._iron : num
        this.ironSlider.progress = num / this._iron
        editbox.string = num + ''

        this.setNeedTraderCount()
    } 
    onFoodEdit(editbox: EditBox){
        let str = editbox.string
        if(!/^\d+$/.test(str)){
            return
        }
        let num = parseInt(str)
        num = num > this._food ? this._food : num
        this.foodSlider.progress = num / this._food
        editbox.string = num + ''

        this.setNeedTraderCount()
    }

    setNeedTraderCount(){
        let wood = parseInt(this.woodEditBox.string) 
        let mud = parseInt(this.mudEditBox.string) 
        let iron = parseInt(this.ironEditBox.string) 
        let food = parseInt(this.foodEditBox.string) 
        let count = wood + mud + iron + food
        let traderCount = Math.ceil(count / this._traderPacket)
        

        if(traderCount == 0){
            this.needTraderCount.string = ''
        } else {
            this.needTraderCount.string = `需要${traderCount}个商人`
        }

        if(traderCount > this._traderNumCurrent){
            this.needTraderCount.color = Color.RED
        } else{
            this.needTraderCount.color = Color.BLACK
        }

        this._needTraderCount = traderCount
    }

    async onSubmit(){
        if(this._needTraderCount > this._traderNumCurrent){
            UIManager.instance.tip('商人不足')
            return
        }
        if(!this._village){
            UIManager.instance.tip('请选择村庄')
            return
        }

        let wood = parseInt(this.woodEditBox.string) 
        let mud = parseInt(this.mudEditBox.string) 
        let iron = parseInt(this.ironEditBox.string) 
        let food = parseInt(this.foodEditBox.string) 
        let count = wood + mud + iron + food
        if(count == 0){
            return
        }


        await UIManager.instance.showLoading()
        let res = await VillageApi.marketSubmit({
            r1:wood,
            r2:mud,
            r3:iron,
            r4:food,
            kid: this._village.zoneId
        })

        UIManager.instance.closeLoading()

        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.tip('商人已出发')
        this.init()
    }

    clear(){

    }

    async getMarketEvents(){
        let res = await VillageApi.marketEvents()

        for(let t of this._traderList){
            t.destroy()
        }
        this._traderList = []
        
        let eventList:TraderEvent[] = res.data
        console.log(eventList)
        for(let event of eventList){
            let node = instantiate(this.traderPrefab)
            this.content.addChild(node)
            this._traderList.push(node)
            node.getComponent(Trader).setData(event)
        }
    }

    onTraderBack(event:TraderEvent){
        console.log('onTraderBack:', event)

        let have = false
        for(let back of this._traderBackList){
            if(event.eHandle == back.eHandle){
                have = true
            }
        }
        if(have){
            return
        }
        this._traderBackList.push(event)

        let wood = event.wood
        let mud = event.mud
        let iron = event.iron
        let food = event.food
        let count = wood + mud + iron + food
        let traderCount = Math.ceil(count / this._traderPacket)

        UserInfo.instance.traderNumCurrent += traderCount
        this. _traderNumCurrent = UserInfo.instance.traderNumCurrent
        this.traderNum.string = `${this._traderNumCurrent}/${this._traderNum}`
    }
}



